<template>
    <SearchTable
        class="reportTable"
        :columns="projectCol" 
        :data="list"
        :total="total"
        :page.sync="query.pageIndex"
        :size.sync="query.pageSize"
        @queryFun="getReportList">
      <template slot="search">
        <Select filterable
            v-model="query.questionId"
            placeholder="请选择题目"
            @on-change="debounceSearch"
            filterable
            style="width:280px;"
          >
            <Option :value="item.targetId" v-for="item in targetList" :key="item.id" :title="item.targetName">{{
              item.targetName
            }}</Option>
        </Select>
        <Input
          v-model.trim="query.fileName"
          clearable
          @on-change="debounceSearch"
          placeholder="报告名称"
        />
        <Button @click="refresh"><i class="el-icon-refresh-right"/></Button>
      </template>
      
      <Modal
        v-model="reportGradeModal.show"
        :title="reportGradeModal.title"
        :loading="reportGradeModal.loading"
        width="800px"
        @on-ok="reportGrade"
        @on-cancel="closeModal"
        :mask-closable="false"
    >
        <Form
            ref="gradeValidate"
            :model="gradeValidate"
            :rules="ruleValidate"
            :label-width="120"
        >
            <!-- <FormItem label="攻击类型" prop="attackType" key="attackType">
                <Select filterable
                    v-model="gradeValidate.attackType"
                    filterable
                    placeholder="攻击类型"
                    @on-change="changeAttackType"
                >
                    <Option
                        :value="item.category"
                        v-for="(item, index) in selRuleList"
                        :key="`type-${item.id}-${index}`"
                        :title="item.category"
                        >{{ item.category }}</Option
                    >
                </Select>
            </FormItem>
            <FormItem label="危害程度" prop="attackLevel">
                <Select filterable v-model="gradeValidate.attackLevel" filterable placeholder="危害程度">
                    <Option
                        :value="item.mold"
                        v-for="(item, index) in attackLevelList"
                        :key="`level-${item.id}-${index}`"
                        :title="item.mold"
                        >{{ item.mold }}</Option
                    >
                </Select>
            </FormItem>
            <FormItem label="类别" prop="targetType" v-if="avaiRuleList.length > 1">
                <RadioGroup v-model="gradeValidate.targetType" type="button">
                    <Radio
                        v-for="item in avaiRuleList"
                        :label="item.targetType"
                        :key="item.id"
                        >{{
                            item.targetType === '1'
                                ? '一类'
                                : item.targetType === '2'
                                ? '二类'
                                : '三类'
                        }}</Radio
                    >
                </RadioGroup>
            </FormItem>
            <FormItem label="危险等级" prop="level">
                <RadioGroup v-model="gradeValidate.level" type="button">
                    <Radio label="high">高危</Radio>
                    <Radio label="middle">中危</Radio>
                    <Radio label="low">低危</Radio>
                </RadioGroup>
            </FormItem> -->
            <FormItem label="分值" prop="score">
                <InputNumber
                    :min="0"
                    :step="1"
                    v-model="gradeValidate.score"
                    placeholder="请输入分值"
                ></InputNumber>
                <!-- <Alert
                    type="warning"
                    show-icon
                    v-show="currentRule && currentRule.description"
                    class="points-tip"
                    >分值标准：{{ currentRule.description }}</Alert
                    > -->
            </FormItem>
            <FormItem label="审核意见" prop="approvalInfo">
                <Input
                    v-model.trim="gradeValidate.approvalInfo"
                    clearable
                    type="textarea"
                    :maxlength="1000"
                    :autosize="{ minRows: 4, maxRows: 8 }"
                    placeholder="审核意见"
                ></Input>
            </FormItem>
        </Form>
    </Modal>
    </SearchTable>
  </template>
  <script>
  import {debounce} from '@/libs/utils'
  import {
    getRefereeCtfReportList,
    getRefereeCtfTaskList,
    reportGrade,
    getRefereeAllotTargetList
  } from '@/api/drill_compete.js';
  import encryption from '@/libs/encryption.js'
  export default {
    components: {  },
    data() {
        const validatePoints = (rule, value, callback) => {
            if (value || value === 0) {
                if (!Number.isInteger(value)) {
                    callback(new Error('请输入整数'));
                } else {
                    if (value < 0 || value > 100000) {
                        callback(new Error('分值范围0~100000'));
                    } else {
                        callback();
                    }
                }
            } else {
                callback(new Error('不能为空'));
            }
        };
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
      return {
        USER_ID: September.userId,
        ...this.$route.query,
        // 工程列表
        query:{
            pageIndex:1,
            pageSize:10
        },
        list: [],
        total: 0,
        projectCol: [
          {
            title: '报告名称',
            key: 'fileName',
            minWidth: 120,
            placement: 'top-left'
          },
          {
            title: '题目名称',
            key: 'questionName',
            width: 100,
            tooltip: true
          },
          {
            title: '团队名称',
            key: 'teamName',
            width: 100,
            tooltip: true
          },
          {
            title: '审核状态',
            key: 'status',
            placement: 'top-right',
            width: 80,
            render: (h, params) => {
                let color = '';
                let text = '';
                let status = params.row.status ? params.row.status : 1;
                // if (status === 3) {
                // color = 'error';
                // text = '已驳回';
                // } else if (status === 2) {
                // color = 'success';
                // text = '已通过';
                // } else if (status === 1) {
                // color = 'primary';
                // text = '未审核';
                // } else if (status === 4) {
                // color = 'default';
                // text = '已挂起';
                // } else if (status === 5) {
                // color = 'primary';
                // text = '驳回后再提交';
                // }
                return h('span', [
                h(
                    'Tag',
                    {
                    props: {
                        //                                      type:'dot',
                        color: status === 1 ? 'var(--status-no)' : 'var(--status-yes)'
                    }
                    },
                    status === 1 ? '未审核' : '已审核'
                )
                ]);
            }
            },
            {
                title: '得分',
                width: 140,
                key: 'score'
            },
            {
                title: '最后审核人',
                key: 'userName',
                width: 200,
                tooltip: true
            },
            {
                title: '审核意见',
                key: 'approvalInfo',
                width: 200,
                tooltip: true
            },
            {
                title: '提交人',
                key: 'userName',
                width: 100,
                tooltip: true
            },
            {
                title: '提交时间',
                key: 'createTime',
                width: 200,
                tooltip: true
            },
            {
                title: '审核',
                align: 'center',
                key: 'action',
                width: 180,
                placement: 'top-right',
                fixed:'right',
                opList:[
                    {
                        txt: '下载',
                        fun: (data) => {
                            this.download(data.fileId);
                        }
                    },
                    {
                        txt: '预览',
                        fun: (data) => {
                            window.openTrain(`/api/minio/filePreview?id=${data.fileId}`);
                        }
                    },
                    {
                        txt: '审核',
                        fun:this.reviewBtn
                    }
                    // {
                    //     txt:(data) => {
                    //     let status = data.status ? data.status : 1;
                    //         return status === 1 ? '审核' : '重新审核'
                    //     },
                    //     on: {
                    //         click: (data) => {
                    //             let status = data.status ? data.status : 1;
                    //             status === 1 ? this.reviewBtn(data) : this.modifyReviewBtn(data);;
                    //         }
                    //     }
                    // }
                ]
            }
        ],
        reportGradeModal: {
            show: false,
            title: '审核',
            loading: true,
        },
        gradeValidate: {
            sceneId: this.$route.query.id,
            attackType: '',
            approvalInfo: '',
            attackLevel: '',
            targetType: '',
            level: '',
            score: 0,
        },
        ruleValidate: {
            attackType: [{ required: true, message: '请选择攻击类型', trigger: 'change' }],
            attackLevel: [{ required: true, message: '请选择危害程度', trigger: 'change' }],
            // targetType: [{ required: true, message: '请选择目标类型', trigger: 'change' }],
            // approvalInfo: [
            //     { required: true, min: 1, message: '请填写审核意见', trigger: 'change' },
            // ],
            // level: [{ required: true, message: '请选择危险等级', trigger: 'change' }],
            score: [
                {
                    required: true,
                    type: 'number',
                    validator: validatePoints,
                    trigger: 'change',
                },
            ],
        },
        ruleList: [],
        selRuleList: [],
        currentTarget: {},
        targetList:[]
      };
    },
    computed: {
        // attackLevelList() {
        //     if (!this.gradeValidate.attackType) {
        //         return [];
        //     }
        //     let list = this.selRuleList;
        //     let type = this.gradeValidate.attackType;
        //     return list.find((item) => item.value === type).children;
        // },
        // currentRule() {
        //     if (this.avaiRuleList.length >= 1) {
        //         return this.avaiRuleList[0];
        //     } else {
        //         return {
        //             id: '',
        //         };
        //     }
        // },
        // avaiRuleList() {
        //     let category = this.gradeValidate.attackType;
        //     if (!(category && this.gradeValidate.attackLevel)) {
        //         return [];
        //     }
        //     let ruleList = this.ruleList.filter(
        //         (item) => item.category === category && item.mold === this.gradeValidate.attackLevel
        //     );
        //     let avaiRuleList = ruleList.filter(
        //         (rule) => rule.targetType === this.currentTarget.category
        //     );
        //     return avaiRuleList.length > 0 ? avaiRuleList : ruleList;
        // },
    },
    created() {},
    watch: {
      
    },
    mounted() {
      this._query = {...this.query};
      this.$store.commit('addBreadItem', { name: this.sceneName });
      // 调用工程列表
      this.getReportList();
      this.getRefereeAllotTargetList();
    },
    methods: {
        // 获取工程列表
        getReportList() {
            getRefereeCtfReportList(this.sceneId,this.query)
            .then(({code,data,message}) => {
                if (code === 1) {
                this.list = data.items;
                this.total = data.total;
                }
            })
            .catch((err) => {});
        },
        debounceSearch:debounce(function(val) {
            this.query.pageIndex = 1;
            this.getReportList();
        },500),
        refresh() {
            this.query = {...this._query};
            this.getReportList();
        },
        reviewBtn(row) {
            this.$refs['gradeValidate'].resetFields();
            this.currentTarget = row;
            // let type = 'attackType';
            // let currentRule = this.ruleList.find((item) => item.id === row[type]) || {};
            // this.isCheckFirst = row.attackType ? true : false;
            this.gradeValidate = {
                // attackType: currentRule.category,
                approvalInfo: row.approvalInfo,
                // attackLevel: currentRule.mold,
                // targetType: currentRule.targetType,
                score: row.score || 0,
                // level: row.level,
                status: row.status
            };
            this.reportGradeModal.show = true;
        },
        // changeAttackType() {
        //     this.gradeValidate.attackLevel = '';
        //     this.gradeValidate.targetType = '';
        //     this.gradeValidate.score = 0;
        //     this.gradeValidate.level = '';
        // },
        // queryHWScoreRule() {
        //     return new Promise((resolve, reject) => {
        //         let query = { pageIndex: 1, pageSize: 100000 };
        //         queryHWScoreRule(this.$route.query.id, query)
        //             .then(({ code, data, message }) => {
        //                 if (code == 1) {
        //                     this.ruleList = data.items;
        //                     //攻击还是防御
        //                     let ruleList = data.items;
        //                     let ruleObj = {};
        //                     ruleList.forEach((rule) => {
        //                         if (!ruleObj[rule.category]) {
        //                             ruleObj[rule.category] = {
        //                                 ...rule,
        //                                 label: rule.category,
        //                                 value: rule.category,
        //                                 children: [rule],
        //                             };
        //                         } else {
        //                             if (
        //                                 !ruleObj[rule.category].children.find(
        //                                     (item) => item.mold === rule.mold
        //                                 )
        //                             ) {
        //                                 ruleObj[rule.category].children.push(rule);
        //                             }
        //                         }
        //                     });
        //                     this.selRuleList = Object.values(ruleObj);
        //                     console.log(this.selRuleList);
        //                     resolve();
        //                 } else {
        //                     this.$Message.error(message);
        //                 }
        //             })
        //             .catch((error) => {
        //                 console.log(error);
        //             });
        //     });
        // },
        reportGrade() {
            this.$refs.gradeValidate.validate((valid) => {
                if (valid) {
                    let params = {
                        sceneId: this.sceneId,
                        questionId: this.currentTarget.questionId,
                        teamId: this.currentTarget.teamId,
                        score: 0,
                        ctfReport: {
                            status: 2,
                            id: this.currentTarget.id,
                            fileId: this.currentTarget.fileId,
                            // attackType: this.currentRule.id,
                            approvalInfo: this.gradeValidate.approvalInfo,
                            // attackLevel: this.currentRule.mold,
                            // targetType: currentRule.targetType,
                            score: this.gradeValidate.score || 0,
                            // level: this.gradeValidate.level,
                        },
                    };
                    reportGrade(params)
                        .then((data) => {
                            if (data.code == 1) {
                                this.reportGradeModal.show = false;
                                this.$Message.info('操作成功');
                                this.getReportList();
                            } else {
                                this.cancelLoading();
                                this.$Message.warning(data.message);
                            }
                        })
                        .catch((error) => {
                            this.cancelLoading();
                        });
                } else {
                    this.cancelLoading();
                }
            })
            .catch(() => {
                this.cancelLoading();
            });
        },
        cancelLoading() {
            this.reportGradeModal.loading = false;
            setTimeout(() => {
                this.reportGradeModal.loading = true;
            }, 500);
        },
        getRefereeAllotTargetList(){
            let query = {
                pageIndex:1, 
                pageSize:10000,
                userId:this.USER_ID
            }
            getRefereeAllotTargetList(this.sceneId,query).then(({code,data,message}) => {
                if(code == 1){
                    this.targetList  = data.items;
                }else{
                    this.list = [];
                    this.total = 0;
                }
            }).catch(error => {
                this.list = [];
                this.total = 0;
            })
        },
        closeModal() {
            this.$refs['gradeValidate'].resetFields();
        },
        // 下载报告
        download(fileId) {
            let a = document.createElement('a');
            document.body.appendChild(a);
            a.href = `/api/minio/download/${fileId}`;
            a.click(); //点击触发下载
            // window.URL.revokeObjectURL(url); //下载完成进行释放
        }
    }
  };
  </script>
  <style scoped>
    .reportTable /deep/ .header {
        justify-content: flex-end;
    }
  </style>
  